import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_yres/model/car/car_cate_model.dart';
import 'package:flutter_yres/model/car/car_merchant_entity.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/services.dart';
import 'package:jlocation/jlocation.dart';
import 'package:flutter_yres/tool/star.dart';
import 'package:flutter_yres/pages/car/merchant_detail.dart';
import 'package:flutter_yres/pages/car/car_sub_page.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import '../pages/user/WebPage.dart';

class CarPage extends StatefulWidget {
  // CarPage({Key key}) : super(key: key);

  @override
  _CarPageState createState() => _CarPageState();
}

class _CarPageState extends State<CarPage> {
  EasyRefreshController _controller = new EasyRefreshController();
  List<CarCateModelData> subs = []; //汽车顶级分类数组
  List<CarMerchantModelData> merchants = []; //商户列表
  List subsImg = [
    'images/icon_menu_wash.png',
    'images/icon_menu_cosme.png',
    'images/icon_menu_repair.png',
    'images/icon_menu_maintain.png',
    'images/icon_menu_all.png'
  ];
  double _listHeight = ScreenUtil.getInstance().setHeight(210); //单个列表高度
  int thepage = 1;
  var jyz_selectDistanceItemValue;
  var jyz_selectoilNoItemValue;
  var jyz_selectCondItemValue;
  var jyz_selectGasTypeItemValue;
  double lat, lng;
  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return Scaffold(
      body: AnnotatedRegion<SystemUiOverlayStyle>(
        child: new Stack(children: <Widget>[
          Container(
              margin: EdgeInsets.fromLTRB(
                  0,
                  ScreenUtil.getInstance().setWidth(60) +
                      MediaQueryData.fromWindow(window).padding.top +
                      20,
                  0,
                  0),
              child: new EasyRefresh(
                // child: Text('data'),
                //刷新  加载组件
                controller: _controller,
                enableControlFinishRefresh: true,
                enableControlFinishLoad: true,
                header: MaterialHeader(),
                footer: MaterialFooter(),
                child:
            //      CustomScrollView(slivers: <Widget>[

            //   SliverGrid(
            //     gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
            //       maxCrossAxisExtent: (ScreenUtil.getInstance().setWidth(750) -
            //               ScreenUtil.getInstance().setWidth(20)) /
            //           5,
            //       mainAxisSpacing: 10.0,
            //       crossAxisSpacing: 10.0,
            //       childAspectRatio: 0.85, //子控件宽高比
            //     ),
            //     delegate: SliverChildBuilderDelegate(
            //       (BuildContext context, int index) {
            //         return ;
            //       },
            //       childCount: subs.length,
            //     ),
            //   ),
            //   SliverFixedExtentList(
            //       delegate: SliverChildBuilderDelegate(_buildListItem,
            //           childCount: merchants.length),
            //       itemExtent: _listHeight),
            // ]),
                 Container(child: Column(
                  children: <Widget>[
                    Container(
                      height: ScreenUtil.getInstance().setHeight(160),
                      child: ListView.builder(
                        shrinkWrap: true,
                        itemBuilder: (BuildContext context, int index) {
                          return _itemBuilder(context, subs[index], index);
                        },
                        scrollDirection: Axis.horizontal,
                        itemCount: subs.length,
                      ),
                    ),
                    ListView.builder(
                      shrinkWrap: true,
                      itemBuilder: (BuildContext context, int index) {
                        return _buildListItem(context, index);
                      },
                      scrollDirection: Axis.vertical,
                      itemCount: merchants.length,
                    ),
                  ],
                )),
                onRefresh: () async {
                  thepage = 1;
                  getList(
                      jyz_selectGasTypeItemValue,
                      jyz_selectDistanceItemValue,
                      jyz_selectoilNoItemValue,
                      jyz_selectCondItemValue);
                },
                onLoad: () async {
                  // thepage++;
                  getList(
                      jyz_selectGasTypeItemValue,
                      jyz_selectDistanceItemValue,
                      jyz_selectoilNoItemValue,
                      jyz_selectCondItemValue);
                },
              )),
          _buildSearch()
        ]),
        value: SystemUiOverlayStyle.dark,
      ),
    );
  }
//  CustomScrollView(slivers: <Widget>[

//               SliverGrid(
//                 gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
//                   maxCrossAxisExtent: (ScreenUtil.getInstance().setWidth(750) -
//                           ScreenUtil.getInstance().setWidth(20)) /
//                       5,
//                   mainAxisSpacing: 10.0,
//                   crossAxisSpacing: 10.0,
//                   childAspectRatio: 0.85, //子控件宽高比
//                 ),
//                 delegate: SliverChildBuilderDelegate(
//                   (BuildContext context, int index) {
//                     return ;
//                   },
//                   childCount: subs.length,
//                 ),
//               ),
//               SliverFixedExtentList(
//                   delegate: SliverChildBuilderDelegate(_buildListItem,
//                       childCount: merchants.length),
//                   itemExtent: _listHeight),
//             ])
  //搜索组件
  _buildSearch() {
    return new Container(
      child: Row(
        children: <Widget>[
          // Expanded(
          //     flex: 1,
          // child:
          Container(
            margin: EdgeInsets.all(0),
            child: FlatButton(
                onPressed: () {},
                child: Row(
                  children: <Widget>[
                    Image.asset(
                      'images/icon_nav_location.png',
                      width: ScreenUtil.getInstance().setWidth(30),
                      height: ScreenUtil.getInstance().setWidth(30),
                    ),
                    Text(
                      "定位",
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance().setSp(18)),
                    ),
                  ],
                )),
          ),
          // ),
          Expanded(
            // flex: 3,
            child: Container(
              // width: ScreenUtil.getInstance().setWidth(445),
              child: new MaterialButton(
                height: ScreenUtil.getInstance().setWidth(60),
                child: Row(
                  children: <Widget>[
                    new Icon(Icons.search, color: Colors.grey),
                    new Text('搜索'),
                  ],
                ),
                onPressed: () {},
                color: Color.fromRGBO(245, 245, 245, 1),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20)),
              ),
            ),
          ),
          // Expanded(
          //     flex: 1,
          //     child:
          Container(
            //  width: ScreenUtil.getInstance().setWidth(35),
            //   height: ScreenUtil.getInstance().setWidth(35),
            margin: EdgeInsets.all(0),
            child: new IconButton(
              color: Colors.white,
              icon: Image.asset('images/icon_nav_order.png',
                  width: ScreenUtil.getInstance().setWidth(30),
                  height: ScreenUtil.getInstance().setWidth(30)),
              onPressed: () {
                // ...
              },
            ),
          )
          // )
        ],
      ),
      width: double.maxFinite,
      // height: kBottomNavigationBarHeight + 40,
      margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
      color: Colors.white,
      padding: EdgeInsets.fromLTRB(
          20, MediaQueryData.fromWindow(window).padding.top, 20, 8),
    );
  }

  //其

  _buildPopHeader() {
    //条件筛选头部
    var header = Container(
      height: ScreenUtil.getInstance().setHeight(40),
      width: ScreenUtil.getInstance().setWidth(750),
      child: Row(
        children: <Widget>[
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '全部',
                      style: TextStyle(
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectDistanceItemValue,
                    items: jyz_distanceItemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectDistanceItemValue = T;
                        _refreshList();
                      });
                    },
                  ),
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '附近',
                      style: TextStyle(
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectoilNoItemValue,
                    items: jyz_oilNotemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectoilNoItemValue = T;
                        _refreshList();
                      });
                    },
                  ),
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '智能排序',
                      style: TextStyle(
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectCondItemValue,
                    items: jyz_condtemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectCondItemValue = T;
                        _refreshList();
                      });
                    },
                  ),
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '筛选',
                      style: TextStyle(
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectGasTypeItemValue,
                    items: jyz_gasTypetemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectGasTypeItemValue = T;
                        _refreshList();
                      });
                    },
                  ),
                ),
              ))
        ],
      ),
    );
    return header;
  }

  Widget _itemBuilder(BuildContext context, item, int index) {
    return InkWell(
        onTap: () {
          // print(item.name);
          String auth;
          if (item.name == '洗车') {
            auth = '3';
          } else if (item.name == '汽车美容') {
            auth = '4';
          } else if (item.name == '汽车维修') {
            auth = '5';
          } else if (item.name == '汽车保养') {
            auth = '6';
          } else if (item.name == '汽车改装') {
            auth = '7';
          }
          Navigator.push(
              context,
              MaterialPageRoute(
                  //导航打开新视图
                  builder: (context) => CarSubPage(
                        pdd_id: item.cat_id,
                        name: item.name,
                        auth: auth,
                      ) //打开第二个页面，并传值，传递值的名称是model
                  ));
        },
        child: Container(
          margin: EdgeInsets.only(left:(ScreenUtil.getInstance().setWidth(750)-ScreenUtil.getInstance().setWidth(90)*subs.length)/(subs.length+4)),
          // child:
           child:Column(
            children: <Widget>[
              Container(
                height: ScreenUtil.getInstance().setWidth(20),
              ),
              item.icon == ''
                  ? Image(
                      image: AssetImage(subsImg[index]),
                      width: ScreenUtil.getInstance().setWidth(90))
                  : CachedNetworkImage(
                      width: ScreenUtil.getInstance().setWidth(90),
                      height: ScreenUtil.getInstance().setWidth(90),
                      fit: BoxFit.fill,
                      imageUrl: Api.BaseUrl + item.icon,
                      placeholder: (context, url) => Image.asset(
                        'images/pic_default.png',
                        width: ScreenUtil.getInstance().setWidth(90),
                        height: ScreenUtil.getInstance().setWidth(90),
                        fit: BoxFit.fill,
                      ),
                      errorWidget: (context, url, error) => Image.asset(
                        'images/pic_default.png',
                        width: ScreenUtil.getInstance().setWidth(90),
                        height: ScreenUtil.getInstance().setWidth(90),
                        fit: BoxFit.fill,
                      ),
                    ),
              Text(
                item.name,
                style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(28)),
              )
            ],
          ),
        ));
  }

  Widget _buildListItem(BuildContext context, int index) {
    return new GestureDetector(
        onTap: () {
          //处理点击事件
          CarMerchantModelData model = merchants[index];
          Navigator.push(
              context,
              MaterialPageRoute(
                  //导航打开新视图
                  builder: (context) => MerchantDetailPage(
                        model: model,
                      ) //打开第二个页面，并传值，传递值的名称是model
                  ));
        },
        child: Container(
            margin: EdgeInsets.fromLTRB(
                0, ScreenUtil.getInstance().setHeight(15), 0, 0),
            child: Column(
              children: <Widget>[
                Row(children: <Widget>[
                  _leftImage(index),
                  Expanded(
                    child: _rightColumn(index),
                  )
                ], crossAxisAlignment: CrossAxisAlignment.start),
                Divider(
                  height: 1,
                )
              ],
            )));
  }

  Widget _pd(Widget w, {double l, double t, double r, double b}) {
    //边距
    return Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setWidth(l) ?? 0,
            ScreenUtil.getInstance().setHeight(t) ?? 0,
            ScreenUtil.getInstance().setWidth(r) ?? 0,
            ScreenUtil.getInstance().setHeight(b) ?? 0),
        child: w);
  }

  Widget _leftImage(int index) {
    //左图
    var image = Container(
      child: merchants[index].merchant_avatar == null
          ? Image.asset('images/pic_default.png')
          : new CachedNetworkImage(
              width: ScreenUtil.getInstance().setHeight(150),
              height: ScreenUtil.getInstance().setHeight(150),
              fit: BoxFit.fill,
              imageUrl: merchants[index].merchant_avatar,
              placeholder: (context, url) => Image.asset(
                'images/pic_default.png',
                width: ScreenUtil.getInstance().setHeight(150),
                height: ScreenUtil.getInstance().setHeight(150),
                fit: BoxFit.fill,
              ),
              errorWidget: (context, url, error) => Image.asset(
                'images/pic_default.png',
                width: ScreenUtil.getInstance().setHeight(150),
                height: ScreenUtil.getInstance().setHeight(150),
                fit: BoxFit.fill,
              ),
            ),
      color: Colors.grey,
    );
    return _pd(image, l: 20, t: 0, r: 5, b: 40);
  }

  Widget _rightColumn(int index) {
    //右内容
    var title = Text(
      merchants[index].merchant_name,
      style: TextStyle(color: Colors.black, fontSize: 16.0),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
    var score = RichText(
      text: TextSpan(style: TextStyle(color: Colors.grey), children: [
        TextSpan(
            text: merchants[index].comment_score + '分',
            style: TextStyle(fontSize: 15.0)),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var distance = RichText(
      text: TextSpan(style: TextStyle(fontSize: 13.0), children: [
        TextSpan(
            text: '¥' + merchants[index].consumption + '/人',
            style: TextStyle(color: Colors.grey)),
        TextSpan(text: '导航', style: TextStyle(color: Colors.orange)),
      ]),
    );
    var address = Text(
      // merchants[index].province +
      merchants[index].city == 'null'
          ? "商家暂未填写"
          : merchants[index].city +
              merchants[index].county +
              merchants[index].detail_address,
      style: TextStyle(color: Colors.grey, fontSize: 13.0),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    return new Column(
      children: <Widget>[
        _pd(title, l: 8, t: 0, r: 10, b: 8),
        Row(
          children: <Widget>[
            _pd(
                new StaticRatingBar(
                  size: 15.0,
                  rate: double.parse(merchants[index].comment_score),
                ),
                l: 8,
                t: 0,
                r: 0,
                b: 0),
            _pd(score, l: 8, t: 0, r: 8, b: 0),
            distance
          ],
        ),
        Row(
          children: <Widget>[
            _pd(
                Image.asset(
                  'images/icon_nav_location.png',
                  width: 13,
                  height: 15,
                  fit: BoxFit.fill,
                ),
                l: 0,
                t: 0,
                r: 0,
                b: 0),
            _pd(address, l: 10, t: 0, r: 10, b: 0),
          ],
        ),
      ],
      crossAxisAlignment: CrossAxisAlignment.start,
    );
  }

//商户参数
  List<DropdownMenuItem> jyz_distanceItemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '1000',
        child: new Text(
          '1千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '3000',
        child: new Text(
          '3千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item3 = new DropdownMenuItem(
        value: '5000',
        child: new Text(
          '5千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item4 = new DropdownMenuItem(
        value: '10000',
        child: new Text(
          '10千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);
    return items;
  }

  List<DropdownMenuItem> jyz_oilNotemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '92',
        child: new Text(
          '#92',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '95',
        child: new Text(
          '#95',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item3 = new DropdownMenuItem(
        value: '98',
        child: new Text(
          '#98',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item4 = new DropdownMenuItem(
        value: '0',
        child: new Text(
          '#0',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);
    return items;
  }

  List<DropdownMenuItem> jyz_condtemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '1',
        child: new Text(
          '油价升序',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '2',
        child: new Text(
          '距离升序',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    return items;
  }

  List<DropdownMenuItem> jyz_gasTypetemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '1',
        child: new Text(
          '中石油',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '2',
        child: new Text(
          '中石化',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item3 = new DropdownMenuItem(
        value: '3',
        child: new Text(
          '壳牌',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item4 = new DropdownMenuItem(
        value: '4',
        child: new Text(
          '其他',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);
    return items;
  }

  @override
  void initState() {
    // print('=====车生活');
    thepage = 1;
    _refreshList();
    super.initState();
    // getLocation();
  }

  // getLocation() {
  //   var loc = new Jlocation();
  //   loc.onLocationChanged().listen((loc) {
  //     setState(() {
  //       if (!mounted) return;
  //       lat = loc.latitude;
  //       lng = loc.longitude;
  //       _refreshList();
  //     });
  //   });
  // }

  void _refreshList() {
    getCarTopCatList();
    // setState(() {
    //   page = 1;
    getList(jyz_selectGasTypeItemValue, jyz_selectDistanceItemValue,
        jyz_selectoilNoItemValue, jyz_selectCondItemValue);
    // });
  }

  getList(gasType, distinct, oilNo, cond) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    //加油站
    Map map = new Map();
    map['page'] = thepage;
    map['per'] = '8';
    // FormData data;
    if (lat == null) {
    } else {
      map['lng_lat'] = lng.toString() + "," + lat.toString();
    }
    print(map);
    FormData fromData = FormData.fromMap(new Map<String, dynamic>.from(map));

    // print(data);
    Response<String> response =
        await HttpUtil().post(Api.GetMerchantListUrl, data: fromData);
    print('=====商户列表$response');

    Map userMap = json.decode(response.data);
    CarMerchantModelEntity jyzEntity =
        new CarMerchantModelEntity.fromJson(userMap);
    if (jyzEntity.code == 1) {
      print(userMap);
      if (mounted) {
        setState(() {
          if (thepage == 1) {
            merchants.clear();
            merchants = jyzEntity.data;
            _controller.finishRefresh();
          } else {
            merchants.addAll(jyzEntity.data);
            _controller.finishLoad();
          }
        });
      }
    }
  }

  getCarTopCatList() async {
    FormData data = new FormData.fromMap({});
    Response<String> response =
        await HttpUtil().post(Api.GetTopCatListUrl, data: data);
    Map userMap = json.decode(response.data);
    // print(userMap);
    CarCateModelEntity itemEntity = new CarCateModelEntity.fromJson(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
          subs.clear();
          subs = itemEntity.data;
        });
      }
    }
  }
}
